<?php
class Patient_history_model extends Mymodel {
	public $table_name = "patient_history";
	public $table_name2 = "patient_checkups";
	public $table_name3 = "patient_examinations";
	
    function Patient_history_model()
    {
        parent::Mymodel();
    }
    
	function get_history($id=NULL,$preview_date=NULL,$limit=NULL)
	{
		
		$this->db->select('*');
		$this->db->from($this->table_name);
		$this->db->join($this->table_name2, 'patient_history.patient_id=patient_checkups.patient_id and  patient_history.id = patient_checkups.preview_id','left');
        $this->db->join($this->table_name3, 'patient_history.patient_id=patient_examinations.patient_id and  patient_history.id =patient_examinations.preview_id','left');
		if($id!==NULL) $this->db->where($this->table_name.'.patient_id', $id);
		if($preview_date!==NULL) $this->db->where($this->table_name.'.preview_date', $preview_date);
		if($limit!==NULL)$this->db->limit($limit);
		
		 $this->db->order_by('preview_date DESC,examination_id ASC,checkup_id ASC');
		$query = $this->db->get();
		$result = $query->result_array();
		#$this->show_the_query();
		#print_r($result);die;
		
		
		return $result;
	}

	function insert_history($data,$checkups,$examinations)
	{
		$this->insert_new_record($this->table_name , $data);
		$preview_id=$this->db->insert_id();
		$checkup_array=$examination_array=array('patient_id'=>$data['patient_id'],'preview_id'=>$preview_id);
		if(!empty($checkups))
		foreach ($checkups as $checkup_id){
		$checkup_array['checkup_id']=$checkup_id;
		$this->insert_new_record($this->table_name2 , $checkup_array);	
		}
		if(!empty($examinations))
		foreach ($examinations as $examination_id){
		$examination_array['examination_id']=$examination_id;
		$this->insert_new_record($this->table_name3 , $examination_array);	
		}
		
		return $preview_id;
	}

}
